<template>
  <el-dialog title="配置角色" :visible="visible" @close="close">
    <el-container v-loading="loading" class="tab-container">
      <el-main style="padding:0px;">
        <el-form :inline="true" label-width="80px">
          <el-formItem label="姓名">
            <el-input :value="userName" disabled />
          </el-formItem>
          <el-formItem label="账号">
            <el-input :value="userAccount" disabled />
          </el-formItem>
        </el-form>
        <el-form label-width="80px">
          <el-form-item>
            <el-transfer v-model="roleIdList" :titles="titles" :data="roleList" />
          </el-form-item>
        </el-form>
      </el-main>
    </el-container>

    <div slot="footer" class="dialog-footer">
      <el-button v-permission="'system:user:configRole'" type="primary" @click="save">保存</el-button>
      <el-button @click="close">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'user-role',
  data() {
    return {
      roleList: [],
      roleIdList: [],
      // TODO：从使用者便利的角度而言，调换两个列表框左右次序更合适
      titles: ['所有角色', '已拥有角色'],
      userName: '',
      userAccount: '',
      loading: false,
      visible: false
    }
  },
  methods: {
    show(id, name, account) {
      this.userId = id
      this.userName = name
      this.userAccount = account
      this.getData(id)
      this.visible = true
    },
    getData(id) {
      const sortInfo = {
        sort_field: 'orderNo',
        sort_sortType: 'ascending'
      }
      // 获取所有角色
      this.$api.system.role.getTransfer(sortInfo)
        .then(res => {
          this.roleList = res.data
          // 获取用户已拥有的角色
          this.$api.system.user.getRole(id)
            .then(res => {
              this.roleIdList = res.data
            })
        })
    },
    save() {
      this.loading = true
      this.$api.system.user.saveRole(this.userId, { roleIdList: this.roleIdList })
        .then(() => {
          this.close()
        })
        .finally(() => {
          this.loading = false
        })
    },
    close() {
      this.visible = false
    }
  }
}
</script>
<style lang='scss' scoped>
.tab-container {
  padding: 15px;
  width: 625px;
}
</style>
